import React,{} from 'react';
import {
  Image,
  Text,
  View,
  Platform,
  StyleSheet,
  TouchableOpacity,
} from 'react-native';
import Dimensions from 'Dimensions';
import {CachedImage} from "react-native-img-cache";

import SizeUtils from '../common/SizeUtils';
import ImageConstants from '../common/ImageConstants';
import TComponent from './TComponent';
import CommonShowImageFullScreenAction from '../actions/common/CommonShowImageFullScreenAction';

export default class TImage extends TComponent {
  constructor(props) {
    super(props);
    //showDefault 是否直接显示默认图，不管是否加载中 true 直接显示
    //useDefault 是否在加载中的时候显示默认图  true 显示
    //translatedSize width和height是否是转换后的尺寸 true是
    //needCache 是否需要缓存
    //onPress = {type:["fullScreen"]}
    //isMini 加载是否是mini图  ?x-oss-process=style/stylename
    // miniSize
    // mini100
    // mini200
    // mini500
    // mini500_q50 表示宽度固定缩放到500，高度按比例自适应，q是质量压缩为50%
    // mini500_q80
    // mini300_q80
    // mini300_q100

    this._needCache = true;
    this.state.isLoading = this.props.source.uri != null && (this.props.source.uri.indexOf("http") > -1);
    this._isLocal = !this.state.isLoading;
    this.state.isLoadComplete = false;
    this.state.progress = 0;
    this.state.error = false;

    this._immutable = true;
    this._isMini = this.props.isMini ? this.props.isMini : false;
    this._miniSize = this.props.miniSize ? this.props.miniSize : "mini200_q80";
  }

  _getSizeStyle() {
    let style = {};
    if(this.props.style.width != undefined) {
      style.width = this.props.translatedSize == true ? this.props.style.width :
        SizeUtils.translateDesignWidthToCode(this.props.style.width);
    }
    if(this.props.style.height != undefined) {
      style.height = this.props.translatedSize == true ? this.props.style.height:
        SizeUtils.translateDesignWidthToCode(this.props.style.height);
    }

    if(Platform.OS == 'android' &&this.props.style.borderRadius != undefined){
      style.borderRadius = this.props.translatedSize == true ? this.props.style.borderRadius:
        this.props.style.borderRadius;
    }
    if(Platform.OS == 'android' &&this.props.style.overflow){
      style.overflow = this.props.style.overflow;
    }
    return style;
  }

  shouldComponentUpdate(nextProps, nextState) {
    return true;
  }

  componentDidMount() {

  }

  componentWillUnmount() {

  }

  componentWillUpdate(nextProps, nextState) {
    let update = false;
    if(nextProps.source.uri != undefined) {
      if(this.props.source.uri != nextProps.source.uri) {
        update = true;
      }
    }
    else if(this.props.source != nextProps.source) {
      update = true;
    }
    if(update) {
      nextState.isLoading = nextProps.source.uri != null && (nextProps.source.uri.indexOf("http") > -1);
      this._isLocal = !nextState.isLoading;
      nextState.isLoadComplete = false;
    }
  }

  _observer(path) {
    console.log(`path of the image in the cache: ${path}`);
  };

  render() {
    return(
      <TouchableOpacity style={[this._getThisStyle(),this._getSizeStyle()]}
          disabled={this.props.onPress === undefined} onPress={this._onPress.bind(this)}>
        {this._renderLoadingText()}
        {this._renderImage()}
      </TouchableOpacity>
    )
  }

  _onPress() {
    if(this.props.onPress && this.props.onPress.type && (this.props.onPress.type instanceof Array) &&
      this.props.onPress.type.indexOf("fullScreen") > -1) {
        if(this.props.source.uri != null && (this.props.source.uri.indexOf("http") > -1)) {
          new CommonShowImageFullScreenAction().call(this, {source:this.props.source.uri, isNeedSave:true})
        }
      }
  }

  _getThisStyle(){
    return Platform.OS == 'android' ?{}:this.props.style;
  }

  _renderLoadingText() {
    // if(this.state.isLoading === true || (this.props.showDefault && !this.state.isLoadComplete)) {
    //   return(
    //     <View style={[{backgroundColor:"#eff1ff", flexDirection:"row",justifyContent:"center", alignItems:"center"}, this._getSizeStyle()]}>
    //       {this._renderDefaultImage()}
    //       <Text style={[this._getSizeStyle(), {textAlign:"center", color:"#000000",
    //           backgroundColor:"#00000000",
    //           fontSize:SizeUtils.translateFontSizeToCode(18),
    //           position:"absolute", top:SizeUtils.translateDesignHeightToCode(10)}]}>
    //         {this._getLoadingText()}
    //         {this.state.isLoading ? this.state.error : ""}
    //       </Text>
    //     </View>
    //   )
    // }
  }

  _getLoadingText() {
    if(this._needCache) {
      return "加载中...";
    }
    return this.state.isLoading ? ("加载中..." + this.state.progress + "%") : "";
  }

  _renderDefaultImage() {
    if(this.props.useDefault != false) {
      return <Image source={ImageConstants.common_default_ad}
                style={{width:SizeUtils.translateDesignWidthToCode(64),
                  height:SizeUtils.translateDesignWidthToCode(55)}}/>;
    }
  }

  _renderImage() {
    if(this._isLocal === false && this._needCache === true) {
      return this._renderCacheImage();
    }
    else {
      if(!this.state.isLoading) {
        return this._renderLocalImage();
      }
      else {
        return  this._renderImageLoader();
      }
    }
  }

  _renderLocalImage() {
    return(
      <View style={[{backgroundColor:"#00000000", flexDirection:"row", justifyContent:"center", alignItems:"center"}, this._getSizeStyle()]}>
        <Image
          source={this.props.source}
          resizeMode={this.props.resizeMode}
          style={this._getSizeStyle()}
        />
      </View>
    )
  }

  _renderCacheImage() {
    if(this._isLocal === false) {
      return (
        <CachedImage
          source={this._getSource()}
          resizeMode={this.props.resizeMode}
          style={[this._getSizeStyle(), {position:"absolute", top:0,left:0,overflow:"hidden"}]}
      />)
    }
  }

  _getSource() {
    //假如使用缩略图
    if(this._isMini) {
      //假如用的是阿里云的图片
      if(this.props.source.uri && this.props.source.uri.indexOf("http://dqapp.oss-cn") > -1) {
        let uri = this.props.source.uri;
        uri = uri + "?x-oss-process=style/" + this._miniSize;
        return {uri:uri};
      }
    }
    return this.props.source;
  }

  _renderImageLoader() {
    return(
      <Image
        source={this.props.source}
        style={{width:1, height:1}}
        resizeMode={this.props.resizeMode}
        onLoadStart={(e) => this._onLoadStart(e)}
        onError={(e) => this.setState({error: e.nativeEvent.error})}
        onProgress={(e) => this.setState({progress: Math.round(100 * e.nativeEvent.loaded / e.nativeEvent.total)})}
        onLoad={(event) => this._loadImageComplete(event)}
      />
    )
  }

  _onLoadStart(e) {
    this.setState({isLoading: true, isLoadComplete:false});
  }

  _loadImageComplete(event) {
    this.setState({isLoading: false, isLoadComplete:true, progress:100});
  }
}
